package com.devo.icecream.ui.order

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.devo.icecream.R
import com.devo.icecream.data.CouponBean
import com.devo.icecream.data.IngredientsBean
import com.devo.icecream.data.Pay
import com.devo.icecream.data.ProductBean
import com.devo.icecream.ui.theme.Grey
import com.devo.icecream.ui.theme.IcecreamTheme
import com.devo.icecream.ui.theme.Main
import com.devo.icecream.ui.theme.textGreyColor
import com.devo.icecream.ui.widget.AppPageView
import com.devo.icecream.utils.noRippleClickable
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.delay

private const val qr =
    ""

@OptIn(ExperimentalPagerApi::class)
@Composable
fun OrderScreen(
    urls: List<String> = listOf("https://www.bing.com/th/id/OIP.aMHCdsL-iih-FQMDFtQkSQAAAA?pid=ImgDet&rs=1"),
    orderStatus: OrderStatus = OrderStatus.None,
    product: ProductBean? = null,
    price: Float = -1.0f,
    payType: Pay = Pay.WX,
    diyIngredients: List<IngredientsBean> = listOf(),
    temperature: Float = 0f,
    servicePhone: String = "13290040909",
    countDown: Long = 90,
    coupon: CouponBean? = null,
    onCouponChanged: (code: String) -> Unit = {},
    onSwitchPayType: () -> Unit = {},
    onBack: () -> Unit = {},
) {

    val index = remember(urls) {
        mutableStateOf(urls.size)
    }

    val pagerState = rememberPagerState()

    Scaffold(
        backgroundColor = Grey,
        topBar = { TitleBar(orderStatus, countDown, temperature, onBack) }) { contentPadding ->

        Column(
            modifier = Modifier
                .padding(contentPadding)
                .padding(horizontal = 32.dp)
                .fillMaxSize(),
        ) {

            Card(
                modifier = Modifier
                    .weight(0.4f),
                backgroundColor = Color.White,
                shape = RoundedCornerShape(24.dp),
                elevation = 0.dp
            ) {
                if (diyIngredients.isNotEmpty()) {
                    DiyIngredientsLayout(diyIngredients)
                } else {
                    AppPageView(
                        urls = urls,
                        auto = true,
                    )
                }
            }

            Spacer(modifier = Modifier.height(28.dp))

            Card(
                modifier = Modifier
                    .weight(0.6f)
                    .fillMaxWidth(),
                shape = RoundedCornerShape(24.dp),
                elevation = 0.dp
            ) {

                Column(modifier = Modifier.fillMaxSize()) {

                    if (product != null) {
                        ProductInfo(product)
                    }

                    Box(modifier = Modifier.weight(1f)) {
                        Box(modifier = Modifier.align(Alignment.Center)) {
                            when (orderStatus) {
                                is OrderStatus.WaitPaid -> { //等待  0等待中，1正常完成，2料不足退款，3故障维修
                                    WaitPayLayout(
                                        pay = payType,
                                        imageQR = orderStatus.imgUrl,
                                        price = orderStatus.price,
                                        coupon = coupon,
                                        isFinish = false,
                                        //优惠券已更改
                                        onCouponChanged = onCouponChanged,
                                        onSwitchPayType = onSwitchPayType
                                    )
                                }
                                is OrderStatus.Paid -> { // 0等待中，1正常完成，2料不足退款，3故障维修
                                    val status = orderStatus.paid
                                    WaitPayLayout(
                                        pay = payType,
                                        imageQR = status.imgUrl,
                                        price = status.price,
                                        coupon = coupon,
                                        isFinish = true,
                                        //优惠券已更改
                                        onCouponChanged = onCouponChanged
                                    )
                                }
                                is OrderStatus.Making, is OrderStatus.Finish -> {
                                    val process =
                                        if (orderStatus is OrderStatus.Making) orderStatus.progress else 1f
                                    MakingLayout(
                                        product?.name ?: "餐品",
                                        progress = process
                                    ) {
                                        onBack()
                                    }

                                }
                                is OrderStatus.Fail -> {
                                    if (orderStatus.code == MakeError.IngredientsLackError) {
                                        MakeFailLayout(product?.salePrice ?: price) {
                                            onBack()
                                        }
                                    } else if (orderStatus.code == MakeError.DeviceError) {
                                        MakeErrorLayout(product?.salePrice ?: price)
                                    }
                                }
                            }
                        }
                    }
                }
            }


            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 24.dp)
            ) {

                if (orderStatus !is OrderStatus.Making) {
                    Row(
                        modifier = Modifier
                            .align(Alignment.CenterStart)
                            .noRippleClickable { onBack() },
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        Icon(
                            painter = painterResource(id = R.mipmap.back),
                            modifier = Modifier.size(28.dp),
                            contentDescription = "",
                            tint = textGreyColor
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text(
                            text = "返回食谱",
                            fontSize = MaterialTheme.typography.h1.fontSize,
                            color = textGreyColor
                        )
                    }
                }

                Text(
                    color = textGreyColor,
                    modifier = Modifier
                        .align(Alignment.Center),
                    text = "美味热线：$servicePhone",
                    textAlign = TextAlign.Center,
                    fontSize = 28.sp
                )

            }
        }
    }

    LaunchedEffect(null) {
        while (true) {
            delay(5 * 1000)
            index.value += 1
            if (pagerState.pageCount > 0) {
                pagerState.animateScrollToPage(index.value % pagerState.pageCount)
            }
        }
    }

}


/**
 * 选中商品详情
 * @param product ProductBean
 */
@Composable
fun ProductInfo(product: ProductBean) {

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(150.dp)
            .padding(horizontal = 32.dp, vertical = 16.dp)
    ) {

        AsyncImage(
            modifier = Modifier
                .fillMaxHeight()
                .aspectRatio(1f)
                .background(Main),
            model = product.coverPic,
            contentDescription = "",
            contentScale = ContentScale.Crop
        )

        Spacer(modifier = Modifier.width(16.dp))

        Column(
            modifier = Modifier
                .fillMaxHeight()
                .weight(1f),
            horizontalAlignment = Alignment.Start,
            verticalArrangement = Arrangement.SpaceAround
        ) {

            Text(
                text = product.name,
                style = MaterialTheme.typography.h2
            )

            Text(text = product.ingredientStr, style = MaterialTheme.typography.subtitle1)

        }

        Spacer(modifier = Modifier.width(16.dp))

        Column(
            modifier = Modifier
                .fillMaxHeight()
                .width(IntrinsicSize.Max),
            horizontalAlignment = Alignment.End,
            verticalArrangement = Arrangement.SpaceAround
        ) {
            Text(text = "1份", style = MaterialTheme.typography.h2)

            Text(
                buildAnnotatedString {
                    withStyle(
                        SpanStyle(
                            fontSize = MaterialTheme.typography.h3.fontSize,
                            color = Main
                        )
                    ) {
                        append("￥")
                    }
                    withStyle(
                        SpanStyle(
                            fontSize = MaterialTheme.typography.h2.fontSize,
                            fontWeight = FontWeight.Bold,
                            color = Main
                        )
                    ) {
                        append("%.02f".format(product.salePrice))
                    }
                },
            )

        }


    }

}


/**
 *支付界面title
 * @param countDown Int
 * @param onBack Function0<Unit>
 */
@Composable
private fun TitleBar(
    orderStatus: OrderStatus,
    countDown: Long = 90,
    temperature: Float = 0f,
    onBack: () -> Unit = {}
) {
    Box(
        modifier = Modifier
            .padding(horizontal = 32.dp)
            .fillMaxWidth(),
    ) {
        if (orderStatus !is OrderStatus.Making) {
            Row(
                modifier = Modifier
                    .align(Alignment.CenterStart)
                    .noRippleClickable { onBack() },
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Icon(
                    painter = painterResource(id = R.mipmap.back),
                    modifier = Modifier.size(28.dp),
                    contentDescription = "",
                    tint = textGreyColor
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "返回食谱",
                    fontSize = MaterialTheme.typography.h1.fontSize,
                    color = textGreyColor
                )
            }
        }


        Image(
            modifier = Modifier
                .noRippleClickable { onBack() }
                .align(Alignment.Center)
                .padding(vertical = 30.dp)
                .fillMaxWidth(fraction = 0.25f)
                .wrapContentHeight(),
            painter = painterResource(id = R.mipmap.logo),
            contentScale = ContentScale.FillWidth,
            contentDescription = "logo"
        )

        Text(
            modifier = Modifier.align(Alignment.CenterEnd),
            text = "${countDown}s",
            fontSize = MaterialTheme.typography.h1.fontSize,
            fontWeight = FontWeight.Bold,
            color = Main
        )
    }
}

@Preview(heightDp = 2000, widthDp = 1440)
@Composable
fun OrderPreview() {
    IcecreamTheme {
        OrderScreen()
    }
}
